﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Lucene.Net.Index;
using PaliTextReader2.ContentsDSTableAdapters;
using PaliTextReader2.Utilities;
using Lucene.Net.Documents;
using System.Text.RegularExpressions;
using Lucene.Net.Analysis;
using System.IO;

namespace PaliTextReader2
{
    public partial class IndexingProgressDlg : Form
    {
        bool m_bIsCanon;

        public IndexingProgressDlg(bool bIsCanon)
        {
            InitializeComponent();
            m_bIsCanon = bIsCanon;
        }

        private void IndexingProgressDlg_Load(object sender, EventArgs e)
        {
            ctlWorker.RunWorkerAsync();
        }

        private void IndexCanon(BackgroundWorker worker, DoWorkEventArgs e)
        {
            IndexWriter writer = new IndexWriter(Utility.CanonIndexDirectory, new SimpleAnalyzer(), true);
            writer.SetUseCompoundFile(true);
            writer.SetMaxFieldLength(0x7fffffff);

            FilesTableAdapter objFilesTA = new FilesTableAdapter();
            ContentsDS.FilesDataTable objFilesDT = objFilesTA.GetData();
            int nRowCount=0;

            foreach (ContentsDS.FilesRow objRow in objFilesDT.Rows)
            {
                string str = Utility.GetBookContent(Utility.CanonDirectory, objRow.FileName);

                Document doc = new Document();
                doc.Add(new Field("text", FileIndexer.GetPlainText(str), Field.Store.NO, Field.Index.TOKENIZED, Field.TermVector.WITH_POSITIONS_OFFSETS));
                doc.Add(new Field("file", objRow.FileID.ToString(), Field.Store.YES, Field.Index.UN_TOKENIZED));
                writer.AddDocument(doc);

                worker.ReportProgress((int)((float)nRowCount*100 / (float)objFilesDT.Rows.Count));
                nRowCount++;

                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    break;
                }
            }

            if (!e.Cancel)
                writer.Optimize();

            writer.Close();
        }

        private void IndexPED(BackgroundWorker worker, DoWorkEventArgs e)
        {
            IndexWriter writer = new IndexWriter(Utility.PEDIndexDirectory, new SimpleAnalyzer(), true);
            writer.SetUseCompoundFile(true);
            writer.SetMaxFieldLength(0x7fffffff);

            int nRowCount = 0;
            int PEDLetters = 38;

            for (int i = 1; i < PEDLetters; i++)
            {
                string str = Utility.GetBookContent(Utility.PEDDirectory, i.ToString("00"));

                Document doc = new Document();
                doc.Add(new Field("text", FileIndexer.GetPlainText(str), Field.Store.NO, Field.Index.TOKENIZED, Field.TermVector.WITH_POSITIONS_OFFSETS));
                string strLetter = Regex.Match(str, "<span class=letter><b>([^<]+)</b></span>").Groups[1].Value;
                doc.Add(new Field("letter", strLetter, Field.Store.YES, Field.Index.NO));
                doc.Add(new Field("ID", i.ToString("00"), Field.Store.YES, Field.Index.NO));
                writer.AddDocument(doc);

                worker.ReportProgress((int)((float)nRowCount * 100 / (float)PEDLetters));
                nRowCount++;

                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    break;
                }
            }

            if (!e.Cancel)
                writer.Optimize();

            writer.Close();
        }

        private void ctlCancel_Click(object sender, EventArgs e)
        {
            ctlWorker.CancelAsync();
            ctlCancel.Enabled = false;
        }

        private void ctlWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            if (m_bIsCanon)
                IndexCanon(worker, e);
            else
                IndexPED(worker, e);
        }

        private void ctlWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            ctlProgress.Value = e.ProgressPercentage;
        }

        private void ctlWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled || e.Error!=null)
            {
                string[] arrFiles = null;
                
                if (m_bIsCanon)
                    arrFiles=Directory.GetFiles(Utility.CanonIndexDirectory);
                else
                    arrFiles = Directory.GetFiles(Utility.PEDIndexDirectory);

                foreach (string strFile in arrFiles)
                    File.Delete(strFile);
            }


            Close();
        }
    }
}
